package com.lizk.leetcode.zstr;

/**
 * Z字字符串的问题
 * https://leetcode-cn.com/problems/zigzag-conversion/
 *
 * @author lizhikui
 * @date 2020/8/28 0:19
 */
public class Client {
    public static void main(String[] args) {
        System.out.println(answer("LEETCODEISHIRING", 3));
        System.out.println("LCIRETOESIIGEDHN");
    }

    public static String answer(String s, int numRows) {

        //排除一些特殊情况
        if (s.length() <= 1 || numRows <= 1 || s.length() <= numRows) {
            return s;
        }
        char[] chars = s.toCharArray();
        StringBuffer sb = new StringBuffer();

        //变量定义在循环外部，可以节省内存空间
        int oneStep, twoStep, index;

        for (int i = 0; i < numRows; i++) {
            oneStep = (numRows - i - 1) * 2;    //第一种步长
            twoStep = i * 2;                    //第二种步长
            index = i;                          //当前索引
            sb.append(chars[index]);
            while (index < chars.length) {
                //每次循环处理两个步长,节省循环次数
                if (oneStep != 0 && (index = index + oneStep) < chars.length) {
                    sb.append(chars[index]);
                }
                if (twoStep != 0 && (index = index + twoStep) < chars.length) {
                    sb.append(chars[index]);
                }
            }
        }
        return sb.toString();
    }

}
